package com.yh.csx.event.common.utils;

import com.sun.webkit.graphics.Ref;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Date;

/**
 * @author zhangsheng
 * @date 2021/8/26 11:11
 */
public class ValueUtils {

    public static <T> T values(T ojb) {
        try {
            Arrays.stream(ojb.getClass().getDeclaredFields()).forEach(f -> {
                mackStringValue(ojb, f);
                mackNumberValue(ojb, f);
                mackDateValue(ojb, f);
            });
            return (T) ojb;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static void mackStringValue(Object o, Field f) {
        if (String.class.isAssignableFrom(f.getType())) {
            ReflectionUtils.makeAccessible(f);
            ReflectionUtils.setField(f, o, f.getName());
        }
    }

    private static void mackDateValue(Object o, Field f) {
        if (Date.class.isAssignableFrom(f.getType())) {
            ReflectionUtils.makeAccessible(f);
            ReflectionUtils.setField(f, o, new Date());
        }
    }

    private static void mackNumberValue(Object o, Field f) {
        if (Long.class.isAssignableFrom(f.getType()) || Integer.class.isAssignableFrom(f.getType())) {
            ReflectionUtils.makeAccessible(f);
            Object value = ReflectionUtils.invokeMethod(ReflectionUtils.findMethod(f.getType(), "valueOf", String.class), o,"1");
            ReflectionUtils.setField(f, o, value);
        }
    }
}
